'use strict';

// 导入模块
let fs = require("fs");
let path = require("path");
let router = require("koa-router")();

// 查找目录下的文件
function searchdir(){
    let files = fs.readdirSync(__dirname);
    let fullpath = files.filter(filename=>{
        return filename.endsWith(".js")&&filename!=="index.js";
    })
    return fullpath;
}

// 注册路由
function registerRouter(files){
    files.forEach(item => {
        let fullpath = path.join(__dirname,item);
        let show = require(fullpath);

        for(let i in show){
            let type = show[i][0];
            let fn = show[i][1];

            if(type==="get"){
                router.get(i,fn);
            }else if(type==="post"){
                router.post(i,fn);
            }else{
                console.log("请求类型错误！！！");
            }
        }
    });
}

// 暴露模块
module.exports=function(){
    let files = searchdir();
    registerRouter(files);

    return router.routes();
}
